import optparse

class OptionParser (optparse.OptionParser):

    def exists(self, opt):
        '''Checks if value is set for the given option'''
        option = self.get_option(opt)
        return ((getattr(self.values, option.dest) is None) == False)


def parse_array(option, opt_str, value, parser, to_int = False):
  
    if (len(str(value).strip()) == 0): 
        raise OptionValueError("Expecting key value")
    tokens = value.split(',')
    if to_int:
        try:
            tmp = []
            for token in tokens: tmp.append(int(token))
            tokens = tmp
        except: 
            raise OptionValueError("Expecting integer value.")
    setattr(parser.values, option.dest, tokens)

def handle_delimiter(option, opt_str, value, parser):
    if(len(str(value).strip())==0):
        raise OptionValueError("Expecting delimiter")
    if(value == "tab"):
        setattr(parser.values, option.dest, "\t")
    elif(value == "pipe"):
        setattr(parser.values, option.dest, '|')
    else:
        setattr(parser.values, option.dest, value)
        
    

def parse_int_array(option, opt_str, value, parser):
    return parse_array(option, opt_str, value, parser, True)

def parse_string_array(option, opt_str, value, parser):
    return parse_array(option, opt_str, value, parser, False)


